package system

import (
	"context"
	"encoding/json"
	"github.com/wailsapp/wails/v2/pkg/runtime"
	"strings"
)

const EventName = "system"

type Request struct {
	Channel string
	Type    string
	Payload interface{}
}

type Response struct {
	Data interface{}
}

func EventsHandler(ctx context.Context, optionalData ...interface{}) {
	request := new(Request)
	err := json.Unmarshal([]byte(optionalData[0].(string)), request)
	if err != nil {
		return
	}
	runtime.LogDebugf(ctx, "%+v", request)
	types := strings.Split(request.Type, ":")
	if len(types) <= 1 {
		return
	}

	module := types[0]
	method := types[1]

	switch module {
	case TypeCPU:
		switch method {
		case "info":
			runtime.EventsEmit(ctx, request.Channel, &Response{GetCpuInfo()})
		}
	case TypeDisk:
		switch method {
		case "partitions":
			runtime.EventsEmit(ctx, request.Channel, &Response{GetDiskPartitions()})
		case "usage":
			diskPath := request.Payload.(string)
			runtime.EventsEmit(ctx, request.Channel, &Response{GetDiskUsage(diskPath)})
		case "scan":
			path := request.Payload.(string)
			data, err := ScanDir(path)
			runtime.EventsEmit(ctx, request.Channel, &Response{data})
			if err != nil {
				panic(err)
			}
		}
	}
}
